rm(list = ls())

library(tidyverse)
library(fixest)

## Load data 
## Code immigrant composition classes 

dat <- readRDS('data/civey_clean.rds') %>% 
  mutate(non_EU_high = ifelse(foreign_non_eu_share > quantile(foreign_non_eu_share, 
                                                              probs = .75, na.rm = T), 1, 0),
         non_EU_low = ifelse(foreign_non_eu_share < quantile(foreign_non_eu_share, 
                                                             probs = .25, na.rm = T), 1, 0),
         EU_high = ifelse(foreign_eu27_share > quantile(foreign_eu27_share, 
                                                        probs = .75, na.rm = T), 1, 0),
         EU_low  = ifelse(foreign_eu27_share < quantile(foreign_eu27_share, 
                                                        probs = .25, na.rm = T), 1, 0))

## Code cases of foreign_non_eu_share_bin and foreign_share_tot_bin

dat <- dat %>%
  mutate(
    mig_comp = case_when(
      non_EU_high == 1 ~ 'High non-EU',
      non_EU_low == 1 & EU_high == 1 ~ 'High EU, low non-EU',
      non_EU_low == 1 & EU_low == 1 ~ 'Low EU & Low non-EU',
      TRUE ~ NA_character_
    ),
    mig_comp = factor(mig_comp, levels = c('High non-EU', 'High EU, low non-EU', 'Low EU & Low non-EU')))

## Estimate Main spec by subset

m1 <- feols(vote_afd ~ treated_post | user_id + date, 
            data = dat,
            split = ~ mig_comp, 
            cluster = ~ user_id) 

etable(m1)

